package wyu.service;

import com.baomidou.mybatisplus.core.injector.methods.SelectPage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dto.Result;
import com.entity.Post;
import com.entity.PostBar;
import com.entity.User;
import com.tool.FileTool;
import com.url.FilePathBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import wyu.mapper.PostMapper;
import wyu.service.feign.PostBarFeign;
import wyu.service.feign.UserBarFeign;
import wyu.service.feign.UserFeign;
import wyu.service.feign.UserPostFeign;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Resource
    UserPostFeign userPostFeign;
    @Resource
    UserFeign userFeign;
    @Resource
    PostBarFeign postBarFeign;
    @Resource
    PostMapper postMapper;
    @Resource
    UserBarFeign userBarFeign;

    @Override
    public Integer getPostNumByBarId(int barId) {
        Integer count = query().eq("BAR_ID", barId).count();
        return count;
    }
    //todo=================================
    @Override
    public Result getPostsBySortType(int index, int pageSize, String accordingTo) {
        IPage<Post> iPage = new Page(index,pageSize);
        IPage<Post> page = postMapper.selectPage(iPage, null);
        List<Post> postList = page.getRecords();
        //判断accordingTo的类型
        if (accordingTo.equals("reply")){
            for (Post post : postList) {
                finishAPost(post);
            }
            return Result.ok(postList);
        }
        return null;
    }

    @Override
    public Result publishPost(MultipartFile[] files, int barId, String title, String content, String pure_content, String uname) {
        Post post = new Post();
        post.setBarId(barId);
        post.setUserName(uname);
        post.setTitle(title);
        post.setContent(content);
        post.setPureContent(pure_content);
        Date date = new Date(System.currentTimeMillis());
        post.setPbTime(date);
        //todo 图片未实现多张存储
        String path = FilePathBase.baseUrl + FilePathBase.postImage;
        File filePath = new File(path);  //文件上传路径（不包括文件名）
        try {
            Result result = FileTool.saveImages(files, "", filePath);
            if (result.getResult_code()==200){
                //将图片文件数组转化为图片名称字符串用逗号隔开
                StringBuffer s = new StringBuffer();
                for (MultipartFile file : files) {
                    s.append(file.getOriginalFilename()).append(",");
                    System.out.println(file.getOriginalFilename());
                }
                String imagesStr = s.deleteCharAt(s.length() - 1).toString();//去掉最后一个逗号
                post.setImages(imagesStr);
            }
            save(post);
            return Result.ok();
        }catch (IOException e){
            e.printStackTrace();
        }

        return Result.fail(900,"error- -!");
    }

    @Override
    public Result getPostInfo(int postId,String uName) {
        //todo 当前是否点赞了帖子、是否收藏了帖子
        Map<String,Object> map = new HashMap<>();
        Post post = query().eq("ID", postId).one();
        if (post==null){
            return Result.fail(900,"帖子不存在");
        }
        finishAPost(post);
        map.put("post",post);
        if (uName==""){
            map.put("ubrelevancy",false);
        }
        boolean relevancy = userBarFeign.getUserBarRelevancy(uName, post.getBarId());
        map.put("ubrelevancy",relevancy);
        return Result.ok(map);
    }

    /**
     * 完善一个帖子所需的所有信息
     * @param post
     * @return
     */
    public void finishAPost(Post post){
        int postId = post.getId();
        //设置回复数
        post.setReplyNum(userPostFeign.getReplyNum(post.getId()));
        //设置user信息
        String uName = post.getUserName();
        User user = userFeign.getUserByUname(uName);
        post.setUser(user);
        //设置贴吧信息
        int barId = post.getBarId();
        PostBar postBar = postBarFeign.getById(barId);
        postBar.setPeopleNum(userBarFeign.getCount(barId));
        postBar.setPostNum(getPostNumByBarId(barId));
        post.setPostBar(postBar);
        //设置点赞数
        int subCount = userPostFeign.getSubCount(postId);
        post.setSbcNum(subCount);
        //设置收藏数
        int collectCount = userPostFeign.getCollectCount(postId);
        post.setCollectNum(collectCount);

    }
}
